<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Annotation\EsUp;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Model\FlyShop;
use App\Model\LinkChannel;
use App\Model\Product;
use App\Model\Sku;
use App\Service\EsService;
use App\Service\FlyCartService;
use App\Service\FlyShopFansService;
use App\Service\IndustryService;
use App\Service\ProductService;
use Hyperf\Validation\Rule;
use Hyperf\DbConnection\Db;
Use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;

class ProductController extends AbstractController
{
    /**
     * @Inject
     * @var EsService
     * */
    private $es;

    /**
     * 审核
     * @Inject
     * @var ProductService
     */
    private $productService;

    /**
     * 审核
     * @Inject
     * @var IndustryService
     */
    private $industryService;

    /**
     * 商铺粉丝
     * @Inject
     * @var FlyShopFansService
     */
    private  $fsfs;

    /**
     * @Inject
     * @var FlyCartService
     */
    private $cart;

    public function list()
    {
        // 关键字：名称
        $params = $this->request->all();
        $shop = CurrentShopData::getData();
        $params['shop_id'] = $shop_id =  $shop->id;
        $return =$this->paginate($this->productService->index($params))->toArray();
        if($return){
            foreach ($return['data'] as $key=>$value){
                if($value['sku_list']){
                    $inventory =  array_column($value['sku_list'],'inventory');
                    if(in_array('-1',$inventory)){
                        $return['data'][$key]['total_inventory'] = -1;
                    }
                }
            }
        }

        $return['count_stat'] =$this->productService->countSize(intval($shop->id));
        return $this->jsonResponse->success($return,'数据列表');
    }

    public function shop_list()
    {
        $params = $this->request->all();
        $this->validation(
            $params,
            [
                'shop_id' => [
                    "integer",
                    "min:1",
                    Rule::exists('fly_shop','id')->where('shop_state',1),
                ],
            ],
        );
        return $this->jsonResponse->success($this->paginate($this->productService->index($params,2)), '获取列表成功');
    }

    public function add()
    {
        $params = $this->request->inputs(['product_name',
            'industry_id','delivery_id',
            'main_pic','detail_pic','transport_mode',
            'fileinfo_id',
            'spec_key',
        ]);
        $params['transport_mode'] = isset($params['transport_mode'])?$params['transport_mode']:[];
        if(isset($params['industry_id'])&&$params['industry_id']!=''){
            $industry_info =  $this->industryService->find(intval($params['industry_id']));
            if(!$industry_info){
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'行业不存在');
            }
        }else{
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'行业必填');
        }
        $this->validation(
            $params,
            [
                'product_name' => [
                    "required",
                    "string",
                    "max:255",
                ],
                'industry_id' => [
                    "required",
                    "integer",
                    "min:0",
                ],
                'delivery_id' => [
                    Rule::requiredIf($industry_info['is_unreal']!=1&&in_array(1,$params['transport_mode'])),
                    "integer",
                    "min:0",
                ],
                'transport_mode' => [
                    Rule::requiredIf($industry_info['is_unreal']!=1),
                    "array",
                ],
                'transport_mode.*' => [
                    "required",
                    "integer",
                    "distinct",
                    "between:1,3",
                ],
                'fileinfo_id'=> [
                    "integer",
                ],
                'main_pic' => [
                    "required",
                    "array",
                    "max:6",
                ],
                'main_pic.*' => [
                    "required",
                    "integer",
                    Rule::exists('fileinfo','fileinfo_id'),
                ],
                'detail_pic' => [
                    "array",
                    "max:9",
                ],
                'detail_pic.*' => [
                    "integer",
                    Rule::exists('fileinfo','fileinfo_id'),
                ],
                'spec_key' => [
                    "array",
                ],
            ],
        );

        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $shop_info = CurrentShopData::getData();
        $params['shop_id']   = $shop_info->id;
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['create_by'] = $admin_id;
        try {
            $product_id =  $this->productService->insert(Common::filter_null($params));
            if($product_id){
                Db::commit();
                $spec_key=  $this->productService->get_spec_key($product_id);
                return $this->jsonResponse->success(['product_id'=>$product_id,'spec_key'=>$spec_key],'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败1');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败2'.$exception->getMessage());
        }

    }

    /**
     * @return Psr7ResponseInterface
     * @EsUp(action="add",type=1)
     */
    public function edit()
    {
         $params = $this->request->inputs(['id','product_name',
             'industry_id','delivery_id',
                'main_pic','detail_pic','transport_mode',
             'fileinfo_id',
                'spec_key',
         ]);
        $params['transport_mode'] = isset($params['transport_mode'])?$params['transport_mode']:[];

        if(isset($params['industry_id'])&&$params['industry_id']!=''){
            $industry_info =  $this->industryService->find(intval($params['industry_id']));
            if(!$industry_info){
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'行业不存在');
            }
        }else{
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'行业必填');
        }
         $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    "min:0",
                    Rule::exists('fly_product','id')
                        ->whereNot('check_status','0')
                        ->whereNull('deleted_at'),
                ],
                'product_name' => [
                    "required",
                    "string",
                    "max:255",
                ],
                'industry_id' => [
                    "required",
                    "integer",
                    "min:0",
                ],
                'delivery_id' => [
                    Rule::requiredIf($industry_info['is_unreal']!=1&&in_array(1,$params['transport_mode'])),
                    "integer",
                    "min:0",
                ],
                'transport_mode' => [
                    Rule::requiredIf($industry_info['is_unreal']!=1),
                    "array",
                ],
                'transport_mode.*' => [
                    "required",
                    "integer",
                    "distinct",
                    "between:1,3",
                ],
                'fileinfo_id'=> [
                    "integer",
                ],
                'main_pic' => [
                    "required",
                    "array",
                    "max:6",
                ],
                'main_pic.*' => [
                    "required",
                    "integer",
                    Rule::exists('fileinfo','fileinfo_id'),
                ],

                'detail_pic' => [
                    "array",
                    "max:9",
                ],
                'detail_pic.*' => [
                    "integer",
                    Rule::exists('fileinfo','fileinfo_id'),
                ],
                'spec_key' => [
                    "array",
                ],
                 'spec_key.*.id' => [
                     "integer",
                     Rule::exists('fly_product_spec_key','id')->where('product_id',$params['id']),
                 ],
                 'spec_key.*.spec_name' => [
                     "string",
                     "max:40",
                 ],
            ],
             [
                 'id.exists'=>'不存在或审核中不可修改'
             ]
        );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $shop_info = CurrentShopData::getData();
        $params['shop_id']   = $shop_info->id;
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['update_by'] = $admin_id;
        try {
            if($this->productService->product_update(Common::filter_null($params))){
                Db::commit();
                $spec_key=  $this->productService->get_spec_key($params['id']);
                return $this->jsonResponse->success(['product_id'=>$params['id'],'spec_key'=>$spec_key],'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败：'.$exception->getMessage());
        }
    }


//    可能需要审核的完成认证
    public function edit_link_audit()
    {
        $params = $this->request->inputs([
            'id',
            'channel',
            'landmark_id',
            'is_origin_made',
            'specialty_id',
        ]);
        $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    "min:0",
                    Rule::exists('fly_product','id')
                        ->whereNot('check_status','0')
                        ->whereNull('deleted_at'),
                ],
                'channel' => [
                    "array",
                    "max:6",
                ],
                'channel.*' => [
                    "integer",
                    Rule::exists('fly_channel','id'),
                ],

                'landmark_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('fly_landmark','id'),
                ],
                'specialty_id' => [
                    "integer",
                    "min:0",
                    "max:100",
                ],
                'is_origin_made' => [
                    "required",
                    "boolean",
                ],
            ],
            [
                'id.exists'=>'不存在或审核中不可修改'
            ]
        );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['update_by'] = $admin_id;
        if(isset($params['landmark_id'])&&$params['landmark_id']!=''){

        }else{
            $params['landmark_id'] = 0;
        }
        if(isset($params['specialty_id'])&&$params['specialty_id']!=''){

        }else{
            $params['specialty_id'] = 0;
        }
        try {
            if($this->productService->product_update_link_audit(Common::filter_null($params))){
                Db::commit();
                return $this->jsonResponse->success([],'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败：'.$exception->getMessage());
        }
    }


//    跳过认证
    public function jump_audit()
    {
        $params = $this->request->inputs([
            'id',
        ]);
        $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    "min:0",
                    Rule::exists('fly_product','id')
                        ->whereNot('check_status','0')
                        ->whereNull('deleted_at'),
                ],
            ],
            [
                'id.exists'=>'不存在或审核中不可修改'
            ]
        );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['updated_at'] = $params['push_at'] =  date('Y-m-d H:i:s');
        $params['update_by'] = $admin_id;
        try {
            if($this->productService->product_push(Common::filter_null($params))){
                Db::commit();
                return $this->jsonResponse->success([],'发布成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'发布失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'发布失败：'.$exception->getMessage());
        }
    }

    //   撤销认证
    public function cancel_audit()
    {
        $params = $this->request->inputs([
            'id',
        ]);
        $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    "min:0",
                    Rule::exists('fly_product','id')
                        ->whereNot('check_status','1')
                        ->where('is_illegal','0')
                        ->whereNull('deleted_at'),
                ],
            ],
            [
                'id.exists'=>'不存在或已审核通过不可撤销'
            ]
        );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['updated_at'] = $params['push_at'] =  date('Y-m-d H:i:s');
        $params['update_by'] = $admin_id;
        try {
            if($this->productService->cancel_push($params)){
                Db::commit();
                return $this->jsonResponse->success([],'撤销成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'撤销失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'撤销失败：'.$exception->getMessage());
        }
    }

    public function detail()
    {
        
        $id = $this->request->input('id');
        $this->validation(
            ['id'=>$id],
            [
                'id' => [
                    'required',
                    'string',
                    Rule::exists('fly_product','id')->whereNull('deleted_at'),
                ],
            ],
        );

        $info = $this->productService->info(intval($id));
        if($info){
            $info =  $info->toArray();
            if($this->getAdminId()){
                $info['cart_count'] =   $this->cart->countSkuCate(intval($this->getAdminId()));
            }else{
                $info['cart_count'] = 0;
            }
            if($info['shop_info']){
                $info['shop_info']['fans_num'] = $this->fsfs->getShopFans($info['shop_info']['id']);
            }
        }
        try{
            return $this->jsonResponse->success($info,'信息返回');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'不存在或已删除：'.$exception->getMessage());
        }

    }

    /**
     *
     * @EsUp(action="del",type=1)
     */
    public function del()
    {
        $ids = $this->request->input('ids');
        $shop_info = CurrentShopData::getData();
        $this->validation(
            ['ids'=>$ids],
            [
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_product','id')
                        ->where('shop_id',$shop_info->id)
                        ->whereNull('deleted_at'),
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]
        );
        try{
            $this->productService->deleteByUser($ids,$this->getAdminId());
            foreach ($ids as $v){
                $this->productService->es_push( $v,1);
            }
            return $this->jsonResponse->success([],'删除成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败');
        }
    }

    /**
     * @EsUp(action="add",type=1)
     */
    public function change_show()
    {
        $params = $this->request->inputs(['ids','is_show']);

        $shop_info =  CurrentShopData::getData();
        $this->validation(
            $params,
            [
                "is_show"=>'required|boolean',
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'distinct',
                    'min:0',
                    Rule::exists('fly_product','id')
                        ->where('shop_id',$shop_info->id)
                        ->whereNull('deleted_at')
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]
        );
        Db::beginTransaction();
        try{
            $this->productService->change_show($params['ids'], boolval($params['is_show']),intval($this->getAdminId()));
            foreach ($params['ids'] as $v){
                $this->productService->es_push( $v,1);
            }
            Db::commit();
            return $this->jsonResponse->success([],'修改成功');
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
        }

    }

    /**
     * @EsUp(action="add",type=1)
     */
    public function add_edit_spec()
    {
        $params = $this->request->inputs(['product_id','spec_key']);
        $this->validation(
            $params,
            [
                'product_id' => [
                    "integer",
                    "exists:fly_product,id",
                    "min:0",
                ],
                'spec_key' => [
                    "array",
                    "min:1",
                ],
                'spec_key.*.id' => [
                    "integer",
                    "min:0",
                ],
                'spec_key.*.spec_name' => [
                    "required",
                    "string",
                    "max:40",
                ],
            ],
        );

        Db::beginTransaction();
        try{
            $res = $this->productService->edit_spec($params['spec_key'],intval($params['product_id']));
//            var_dump($res);die;
           if($res==true){
               Db::commit();
               $spec_key=  $this->productService->get_spec_key($params['product_id']);
               return $this->jsonResponse->success(['product_id'=>$params['product_id'],'spec_key'=>$spec_key],'修改成功');
           }else{
               Db::rollBack();
               return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
           }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败'.$exception->getMessage());
        }

    }

    /**
     * 每个状态的记录
     * @return Psr7ResponseInterface
     */
    public function size(): Psr7ResponseInterface
    {
        return $this->jsonResponse->success($this->productService->countSize(1));
    }
}